package Thread;

import java.util.Random;

/*编写代码, 实现多线程数组求和.

        要求如下：
        给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
        实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
        其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
        最终再汇总两个和, 进行相加
        记录程序的执行时间.*/
public class TreadDemo20 {
    private static long result1 = 0;
    private static long result2 = 0;
    private static final int[] tmp = new int[10000000];
    public static void main(String[] args) throws InterruptedException {
        Random rand=new Random();

        for (int i = 0; i < tmp.length; i++) {
            tmp[i] = rand.nextInt(100) + 1;
        }

        long beg = System.currentTimeMillis();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < tmp.length; i+=2){
                result1 += tmp[i];
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 1; i < tmp.length; i+=2) {
                result2 += tmp[i];
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        long total = result1 + result2;
        long end = System.currentTimeMillis();

        System.out.println("奇数下标和偶数下标和为：" + total);
        System.out.println("time = " + (end - beg) + " ms");
    }
}